package cn.woniu.ecommerceplatform.handler;

import cn.woniu.ecommerceplatform.entity.NewUser;
import cn.woniu.ecommerceplatform.util.JWTUtil;
import cn.woniu.ecommerceplatform.util.ResponseResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 前后端分离的的项目情况下,登录成功，返回的不再是一个页面地址,而是一个Json串
 * 处理用户登陆成功后返回数据：比如用户名等信息
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication)
            throws IOException {
        try {
            NewUser user = (NewUser) authentication.getPrincipal();
            Map map =new HashMap<>();
            String jwt= JWTUtil.createJWT(user.getUsername());
            map.put("jwt",jwt);
            map.put("type",user.getType());


//            System.out.println(user);
            //吧jwt 放入redis
            redisTemplate
                    .opsForValue()
                    .set("jwt:"+user.getUsername(), jwt,5, TimeUnit.MINUTES);

            /**
             * 获取登录成功的用户信息
             */
            httpServletRequest.setCharacterEncoding("utf-8");
            httpServletResponse.setCharacterEncoding("utf-8");
            httpServletResponse.setContentType("application/json;charset=utf8");
            PrintWriter writer = httpServletResponse.getWriter();
            String json = JSON.toJSONString(new ResponseResult<>().ok(map));
            writer.print(json);
            writer.flush();
            writer.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
